<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="allLoading"> </a-spin>
      <a-modal
        width="1200px"
        v-model="detailsVisible"
        title="详情信息"
        @cancel="() => (this.detailsVisible = false)"
        destroyOnClose
      >
        <div id="modalContent">
          <Details :id="currentId" :code="form.code"></Details>
        </div>
        <template slot="footer">
          <Button
            type="reset"
            label="关闭"
            @click="
              () => {
                this.detailsVisible = false;
              }
            "
          ></Button>
        </template>
      </a-modal>
      <a-modal
        width="900px"
        v-model="parameterVisible"
        title="参数操作"
        @cancel="() => (this.parameterVisible = false)"
        :confirm-loading="formButtonDisableFlag"
        destroyOnClose
      >
        <div id="modalContent">
          <parameterOperation :id="currentId" :details="form"></parameterOperation>
          <!-- <a-form-model
            ref="formRef"
            :model="params"
            :rules="paramsRules"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
          >
            <a-col :span="24" v-for="(item, index) in params.paramList" :key="'item' + index">
              <a-col :span="10">
                <InputNumber
                  :labelCol="{ span: 12 }"
                  :wrapperCol="{ span: 12 }"
                  :form="item"
                  label="信号量编码"
                  prop="protocolSemaphoreCode"
                  :name="'.paramList.' + index + '.protocolSemaphoreCode'"
                  :rules="{
                    required: true,
                    message: '请输入信号量编码',
                    trigger: 'change',
                  }"
                  placeholder="请输入信号量编码"
                ></InputNumber>
              </a-col>
              <a-col :span="10">
                <InputNumber
                  :labelCol="{ span: 12 }"
                  :wrapperCol="{ span: 12 }"
                  :form="item"
                  label="值"
                  prop="value"
                  :name="'.paramList.' + index + '.value'"
                  :rules="{
                    required: true,
                    message: '请输入值',
                    trigger: 'change',
                  }"
                  placeholder="请输入值"
                ></InputNumber>
              </a-col>
              <a-button type="danger" class="del_one" v-if="index > 0" @click="delParam(index)"> 删除 </a-button>
            </a-col>

            <a-button type="primary" class="addpam_btn" @click="addParams"> 增加参数 </a-button>
          </a-form-model> -->
        </div>

        <template slot="footer">
          <Button
            type="reset"
            label="关闭"
            @click="
              () => {
                this.parameterVisible = false;
              }
            "
          ></Button>
          <!-- <Button type="reset" label="确定" class="addpar_btn" @click="onSubmit"></Button> -->
        </template>
      </a-modal>

      <typicalSearch ref="insideSearch" :searchConfig="searchConfig" @searchMethod="getTableData"></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">参数下发</div>
        </div>
        <div class="tableList">
          <typicalTable
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
          >
            <template v-slot="slotProps">
              <!-- <Button label="详情" @click="handleEdit(slotProps.record, 'detailsVisible')"></Button> -->
              <a-popconfirm
                slot="action"
                title="此操作将重启设备，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="rebootDevice(slotProps.record)"
              >
                <Button type="stop" label="重启"></Button>
              </a-popconfirm>
              <Button label="参数操作" @click="handleEdit(slotProps.record, 'parameterVisible')"></Button>
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
// import { sendCabinetRestart } from '@/api/api';
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import InputNumber from '@/components/typicalControl/InputNumber';
import treeSelect from '@/components/typicalControl/treeSelect';
import Select from '@/components/typicalControl/select';
import Button from '@/components/typicalControl/button';
import Details from './details';
import parameterOperation from './parameterOperation';
import { getYesNo } from '@/utils/frequentInterface';

import { listParameterSending, listNetworksAll, allCharges ,listCabinetModels,equipControl} from '@/api/cabin';
import { organizationsTree } from '@/api/system';

export default {
  name: 'ParameterSending',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Input: Input,
    InputNumber: InputNumber,
    treeSelect: treeSelect,
    Select: Select,
    Button: Button,
    Details: Details,
    parameterOperation: parameterOperation,
  },
  data() {
    return {
      formButtonDisableFlag: false, // 表单确定禁用按钮 防止多次点击多次保存
      allLoading: false,
      detailsVisible: false,
      parameterVisible: false,
      form: {},
      params: { paramList: [{ protocolSemaphoreCode: '', value: '' }] },
      rules: {
        // 规则验证
        name: [{ required: true, message: '请输入设备信息名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入设备信息编号', trigger: 'blur' }],
      },
      paramsRules: {
        // protocolSemaphoreCode: [{ required: true, message: '请输入信号量编码', trigger: 'blur' }],
        // value: [{ required: true, message: '请输入值', trigger: 'blur' }],
      },
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'selectTree',
            prop: 'searchOrganizationId',
            value: undefined,
            label: '组织机构',
            treeData: [],
            change: this.searchOptListDynamicLoading,
          },
          {
            type: 'select',
            prop: 'searchNetworkId',
            value: undefined,
            label: '场站网点',
            optList: [],
          },
         
          {
            type: 'select',
            prop: 'searchModelId',
            value: undefined,
            label: '设备型号',
            optList: [],
          },
          {
            type: 'input',
            prop: 'searchKeyWord',
            value: '',
            label: '名称或编码',
          },
          {
            type: 'select',
            prop: 'searchIsEnable',
            value: undefined,
            label: '是否启用',
            optList: this.getYesNo(),
          },
        ],
        parent: this,
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '名称',
            dataIndex: 'name',
            ellipsis: true,
          },
          {
            title: '充电桩编号',
            dataIndex: 'code',
            ellipsis: true,
          },
          {
            title: '组织机构',
            dataIndex: 'organizationName',
            ellipsis: true,
          },
          {
            title: '场站网点',
            dataIndex: 'chargingNetworkName',
            ellipsis: true,
          },
          {
            title: '设备型号',
            dataIndex: 'chargingCabinetModeName',
            ellipsis: true,
          },
          {
            title: '仓个数',
            dataIndex: 'binCount',
            ellipsis: true,
          },
          {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: true,
          },
          {
            title: '联网状态',
            dataIndex: 'isOnline',
            scopedSlots: { customRender: 'isYesNo' },
            width: '80px',
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            width: '180px',
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      oDictionary: {
        listNetworksAll: [],
        allCabinetTypes: [],
      },
      currentId: '',
    };
  },
  created() {
    this.getDictionary();
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    getYesNo,
    /**
     * [getDictionary 获取各种字典]
     * @return {[type]} [description]
     */
    getDictionary() {
      // 组织列表树形结构数据
      organizationsTree().then((res) => {
        if (res.code == 200) {
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop == 'searchOrganizationId') {
              this.searchConfig.formItemList[i].treeData = res.data;
              break;
            }
          }
        }
      });
      // 场站网点
      this.getNetworkData();
      // 设备类型
      listCabinetModels('/getChargingCabinetModeList?name=&code=&chargingCabinetTypeId=', 'get', { pageNum: 1, pageSize: 20 }).then((res) => {
        if (res.code == 200) {
          this.oDictionary.allCabinetTypes = res.data.records;
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop === 'searchModelId') {
              this.searchConfig.formItemList[i].optList = res.data.records.map((n) => {
                return {
                  name: n.name,
                  code: n.id,
                };
              });
              break;
            }
          }
        }
      });
    },
    getNetworkData(organizationId) {
      // 场站网点
      listNetworksAll(`/selectChargingnetwork`, 'get', {
        pageNum: 1,
        pageSize: 100,
        organizationId: organizationId,
      }).then((res) => {
        if (res.code == 200) {
          this.oDictionary.listNetworksAll = res.data.records.map((n) => {
            return {
              name: n.name,
              code: n.id,
            };
          });
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop == 'searchNetworkId') {
              this.searchConfig.formItemList[i].optList = this.oDictionary.listNetworksAll;
              break;
            }
          }
        }
      });
    },
    /**
     * [searchOptListDynamicLoading 搜索下拉动态加载]
     * @param  {[type]} searchOrganizationId [组织机构id]
     * @return {[type]}                      [description]
     */
    searchOptListDynamicLoading(searchOrganizationId) {
      this.oDictionary.listNetworksAll = [];

      this.getNetworkData(searchOrganizationId);
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      this.allLoading = true;
      let searchData = searchParam ? { ...searchParam } : {};
      let params = {
        pageNum: searchData.pageNumber ? searchData.pageNumber + 1 : 1,
        pageSize: searchData.pageSize ? searchData.pageSize : 10,
        chargingNetworkId: searchParam.searchNetworkId,
        isEnable: searchParam.searchIsEnable,
        nameAndCode: searchParam.searchKeyWord,
        chargingCabinetModeId: searchParam.searchModelId,
        organId: searchData.searchOrganizationId,
      };
      listParameterSending('/selectAll', 'get', params)
        .then((res) => {
          if (res.code == 200) {
            let datas = res.data;
            datas.total=Number(datas.total);
            this.tableData = datas;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.allLoading = false;
        });
    },

    /**
     * @description: 表单新增编辑成功后的公共的代码 （消息提示 搜索框重置 请求表格数据）
     * @param {object} successFormData 表单请求成功后返回的对象
     */
    formSuccessOperation(successFormData) {
      this.$message.success(successFormData.message);
      this.$refs.insideTable.updateListData();
    },
    addParams() {
      this.params.paramList.push({ protocolSemaphoreCode: '', value: '' });
    },
    delParam(index) {
      this.params.paramList.splice(index, 1);
    },
    
    /**
     * [handleEdit 打开详情]
     * @param  {[type]} row          [当前行数据]
     * @param  {[type]} instructions [指令]
     * @return {[type]}              [description]
     */
    handleEdit(row, instructions) {
      this.currentId = String(row.id);
      this[instructions] = true;
      this.form = row;
    },
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    /**
     * [rebootDevice 重启设备]
     * @param  {[type]} row [行数据]
     * @return {[type]}     [description]
     */
    rebootDevice(row) {
      this.allLoading = true;
      equipControl('/restart','get',{ chargingCabinetCode: row.code })
        .then((res) => {
          if (res.code == 200) {
            this.formSuccessOperation({message:'重启成功'});
          }
        })
        .finally(() => {
          this.allLoading = false;
        });
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 650px;
  overflow: auto;
  position: relative;
}

.del_one {
  margin: 3px 20px;
}
/deep/ .ant-col-4{
  width: 20%;
}
</style>
